package com.my.mygaode

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.support.multidex.MultiDex
import android.text.TextUtils

/**
 * @ClassName BaseApplication
 * @Description TODO
 * @Author mwj
 * @Date 2023/7/18 14:47
 * @Version 1.0
 **/
class BaseApplication : Application(){

    companion object {
        private lateinit var INSTANCE: BaseApplication
        fun get() = INSTANCE
    }

    override fun onCreate() {
        super.onCreate()
        INSTANCE = this
        MultiDex.install(this)
        registerLife()
    }

    /**
     * 清除集合的activity
     * @param exceptActivity String 保存对应的某个activity不被清除
     */
    fun exit(exceptActivity: String = "") {
        for (bean in activityList) {
            if (TextUtils.equals(bean.javaClass.name, exceptActivity)) {
                continue
            }
            bean.finish()
        }
    }

    protected val activityList = ArrayList<Activity>()
    private fun registerLife() {
        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                if (!activityList.contains(activity)) {
                    activityList.add(activity)
                }
            }

            override fun onActivityStarted(activity: Activity) {

            }

            override fun onActivityResumed(activity: Activity) {

            }

            override fun onActivityPaused(activity: Activity) {

            }

            override fun onActivityStopped(activity: Activity) {

            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
            override fun onActivityDestroyed(activity: Activity) {
                if (activityList.contains(activity)) {
                    activityList.remove(activity)
                }
            }
        })
    }
}